<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\service\goods\ContentService;
use app\service\goods\TextContentService;
use app\common\model\GoodsOrder;
use app\common\model\User;
use app\common\model\GoodsContentGroup;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsContentManager;
use app\common\model\GoodsContentFile;
use app\common\model\GoodsTag;
use app\common\model\UserFavorite;
use app\common\model\GoodsContentChapter;
use app\common\model\GoodsTagRelation;

class Goods extends Base
{

    // 商品详情
    public function detail()
    {
        $id = request()->post('id');

        $goods = GoodsModel::where([
            'status' => 1,
            'id'     => $id,
        ])->find();

        // 商品判断
        empty($goods) && $this->error(trans('goods_not_exists'));

        // 文章资源型内容处理判断是否已支付
        $goods_paid_content       = $this->getPaidContent($goods->id, $this->user_id);
        $goods->paid_content      = $goods_paid_content['content'];
        $goods->paid_content_type = $goods_paid_content['content_type'];
        $goods->has_paid          = $goods_paid_content['has_paid'] ? true : false;

        // 登录状态下判断是否已经关注店铺
        $goods->is_goods_favorited = false;
        if ($this->user_id) {
            $goods->is_goods_favorited = UserFavorite::isGoodsFavorited($this->user_id, $goods->id);
        }

        // 同栏目的上一篇下一篇
        $goods_prev  = GoodsModel::where('cate_id', $goods->cate_id)->where('id', '<', $goods->id)->field('id,name')->order('sort desc, id desc')->limit(1)->find() ?: [
            'id'   => 0,
            'name' => '没有了'
        ];
        $goods_next  = GoodsModel::where('cate_id', $goods->cate_id)->where('id', '>', $goods->id)->field('id,name')->order('sort desc, id desc')->limit(1)->find() ?: [
            'id'   => 0,
            'name' => '没有了'
        ];
        $goods->prev = [
            'id'   => $goods_prev['id'],
            'name' => $goods_prev['name']
        ];
        $goods->next = [
            'id'   => $goods_next['id'],
            'name' => $goods_next['name']
        ];

        // 浏览次数
        $goods->views += 1;
        $goods->save();

        # 获取商品分类的规格
        $rule_value = $goods?->category?->spec?->rule_value;
        // 获取商品关联规格
        $goods_spec = $goods?->goodsSpec?->spec_value;

        // 正确处理规格信息
        $spec_info = [];
        if ($rule_value && $goods_spec) {
            foreach ($rule_value as $item) {
                if (isset($goods_spec[$item['value']])) {
                    $spec_info[] = [
                        'label' => $item['label'],
                        'value' => $goods_spec[$item['value']]
                    ];
                }
            }
        }
        // 一次性赋值给模型
        $goods->setAttr('spec_info', $spec_info);

        // 获取商品标签
        $goods_tags_relation = GoodsTagRelation::where('goods_id', $id)->column('tag_id');
        if ($goods_tags_relation) {
            $goods_tags = GoodsTag::where('id', 'in', $goods_tags_relation)->column('id,name');
            $goods->setAttr('tags', $goods_tags);
        } else {
            $goods->setAttr('tags', []);
        }


        $goods_visible = ['id', 'price', 'name', 'content', 'buy_need_login', 'slider_image', 'user_id', 'paid_content', 'paid_content_type', 'has_paid', 'sales_volume', 'is_goods_favorited', 'stock_capacity', 'status', 'sold_count', 'create_time', 'prev', 'next', 'views', 'favorites_count', 'comments_count', 'spec_info', 'tags'];
        $goods->visible($goods_visible);

        return $this->success('获取成功', $goods);
    }


    // 商品推荐
    public function recommend()
    {
        $sort    = $this->request->post('sort', 'view');
        $id      = $this->request->post('id', 0);
        $limit   = $this->request->post('limit', 5);
        $cate_id = $this->request->post('cate_id', 0);
        if ($sort == 'view') {
            $order = 'views desc';
        } elseif ($sort == 'sort') {
            $order = 'sort desc, id desc';
        } else {
            $order = 'id desc';
        }
        $where = [
            'status' => 1,
        ];
        if ($cate_id) {
            $where['cate_id'] = $cate_id;
        }
        $goods = GoodsModel::where($where)->field('id,name,slider_image,views,sort, price')->where('id', '!=', $id)->order($order)->limit($limit)->select();
        $this->success('获取成功', $goods);
    }

    /**
     * 获取单个章节内容
     */
    public function chapter()
    {
        $id = request()->post('id', 0);
        if (!$id) {
            return $this->error('参数错误');
        }

        $contentService = new ContentService();
        $goodsId        = 0;
        $hasAuth        = false;

        // 先获取章节的商品ID
        $chapter = GoodsContentChapter::where('id', $id)->find();
        if (!$chapter) {
            return $this->error('章节不存在');
        }

        $goodsId = $chapter->goods_id;

        // 检查用户是否购买

        if ($this->user_id) {
            // 已登录用户
            $user = User::find($this->user_id);

            // 查用户是否已购买
            $hasAuth = $user->canViewContent($goodsId);

        } else {
            // 未登录用户，检查订单号
            $trade_no = request()->get('trade_no') ?: request()->post('trade_no');
            if ($trade_no) {
                $order   = GoodsOrder::where(["trade_no" => $trade_no, 'status' => 1])->find();
                $hasAuth = $order ? true : false;
            }
        }

        // 检查商品价格是否为0（免费）
        $goods = GoodsModel::find($goodsId);
        if ($goods && !$goods->price) {
            $hasAuth = true;
        }

        // 检查章节收费类型
        if ($chapter->is_free) {
            $hasAuth = true;
        }

        // 获取章节内容（已在 ContentService 中处理了上一章下一章和章节目录）
        $chapter = $contentService->getChapterContent($id, $goodsId, $hasAuth, $this->user_id);

        return $this->success('获取成功', $chapter);
    }

    /**
     * 根据商品名查找最后一个章节
     * 无需登录即可访问
     */
    public function findLastChapter()
    {
        $goods_name = request()->post('goods_name', '');
        if (empty($goods_name)) {
            return $this->error('商品名称不能为空');
        }


        $textContentService = new TextContentService();
        $chapter            = $textContentService->findLastChapterByGoodsName($goods_name);

        if (!$chapter) {
            return $this->error('未找到相关章节');
        }

        return $this->success('获取成功', $chapter);

    }

    /**
     * 获取付费内容
     *
     * @param int $goods_id 商品id
     * @param int $user_id 买家id
     * @return array 处理后的内容数据
     */
    protected function getPaidContent($goods_id, $user_id)
    {
        // 确定用户是否有权限查看
        $hasAuth = false;

        // 检查商品价格是否为0（免费）
        $goods = GoodsModel::find($goods_id);
        if ($goods && !$goods->price) {
            $hasAuth = true;
        }


        // 订单号 未登录模式 且传入订单号|优先模式 不判断登录 | 但此url发送给别人的话 别人也可以看到 | nice就这样 可以保证多端查看 用户自发的发送给别人属于自己自发行为 与平台没有什么关系
        $trade_no = request()->get('trade_no') ?: request()->post('trade_no');
        if ($trade_no) {
            $order   = GoodsOrder::where(["trade_no" => $trade_no, 'status' => 1])->find();
            $hasAuth = $order ? true : false;
        }

        // 商品内容没权限 且 用户已登录 则判断用户是否已购买
        if (!$hasAuth && $user_id) {
            $user    = User::find($user_id);
            $hasAuth = $user->canViewContent($goods_id);
        }

        // 获取内容类型
        $contentManager = GoodsContentManager::where('goods_id', $goods_id)->find();
        $contentType    = $contentManager ? $contentManager->type : 'text';
        // 对于多章节图文和分组多章节文本类型，只获取id而不获取内容，提高性能
        if (in_array($contentType, ['multi_file', 'multi_chapter', 'chapter_groups'])) {
            // 使用内容服务获取简化的数据（不含内容）
            if ($contentType == 'multi_file') {
                $files = GoodsContentFile::where('goods_id', $goods_id)
                    ->order('sort asc, id asc')
                    ->field('id,title,sort,is_free,file_url,file_size,description')
                    ->select()
                    ->toArray();

                foreach ($files as &$file) {
                    $file['has_auth'] = $hasAuth;
                    // 如果已经有权限，则直接标记为有权限,不在一一判断
                    if ($hasAuth) {
                        $file['has_auth'] = true;
                    }
                    // 章节设置为免费，则标记为有权限
                    else if ($file['is_free']) {
                        $file['has_auth'] = true;
                    }

                    $file['file_url'] = GoodsContentFile::handleAuthFileUrl($file['file_url'], $file['has_auth']);

                    // has_auth
                    $file['has_auth'] = $hasAuth;
                }

                return [
                    'content'      => [
                        'files' => $files
                    ],
                    'content_type' => $contentType,
                    'has_paid'     => $hasAuth ? 1 : 0
                ];
            } elseif ($contentType == 'multi_chapter') {
                // 获取章节列表（只返回id和标题）
                $chapters = GoodsContentChapter::where('goods_id', $goods_id)
                    ->order('sort asc, id asc')
                    ->field('id,title,sort,is_free,resource_type,video_duration,audio_duration')
                    ->select()
                    ->toArray();
                // 处理章节收费状态
                foreach ($chapters as &$chapter) {
                    $chapterHasAuth = $hasAuth;
                    // 如果已经有权限，则直接标记为有权限,不在一一判断
                    if ($hasAuth) {
                        $chapterHasAuth = true;
                    }
                    // 如果章节设置为免费，则标记为有权限
                    else if ($chapter['is_free']) {
                        $chapterHasAuth = true;
                    }
                    $chapter['has_auth'] = $chapterHasAuth;
                }
                // print_r($chapters);


                return [
                    'content'      => [
                        'chapters' => $chapters
                    ],
                    'content_type' => $contentType,
                    'has_paid'     => $hasAuth ? 1 : 0
                ];
            } else {
                // 分组多章节文本类型
                $groups = GoodsContentGroup::where('goods_id', $goods_id)
                    ->order('sort asc, id asc')
                    ->field('id,title,sort')
                    ->select()
                    ->toArray();

                // 处理分组收费状态
                foreach ($groups as &$group) {
                    // 分组权限是预留,v1.0之前不会去考虑做分组权限
                    $groupHasAuth = $hasAuth;

                    // 如果已经有权限，则直接标记为有权限,不在一一判断
                    if ($hasAuth) {
                        $groupHasAuth = true;
                    }

                    $group['has_auth'] = $groupHasAuth;

                    // 获取分组下的章节
                    $chapters = GoodsContentChapter::where('group_id', $group['id'])
                        ->order('sort asc, id asc')
                        ->field('id,title,sort,is_free,resource_type,video_duration,audio_duration')
                        ->select()
                        ->toArray();

                    // 处理章节收费状态
                    foreach ($chapters as &$chapter) {
                        $chapterHasAuth = $hasAuth;
                        // 如果已经有权限，则直接标记为有权限,不在一一判断
                        if ($hasAuth) {
                            $chapterHasAuth = true;
                        }
                        // 如果章节设置为免费，则标记为有权限
                        else if ($chapter['is_free']) {
                            $chapterHasAuth = true;
                        }

                        $chapter['has_auth'] = $chapterHasAuth;
                    }

                    $group['chapters'] = $chapters;
                }

                return [
                    'content'      => [
                        'groups' => $groups
                    ],
                    'content_type' => $contentType,
                    'has_paid'     => $hasAuth ? 1 : 0
                ];
            }
        } else {
            // 其他类型使用原有方式获取处理后的数据
            $contentService = new ContentService();
            $content        = $contentService->getGoodsPaidContent($goods_id, $hasAuth, $this->user_id);

            // 返回内容数据
            return [
                'content'      => $content,
                'content_type' => $contentType,
                'has_paid'     => $hasAuth ? 1 : 0
            ];
        }
    }

    /**
     * 切换商品收藏状态
     * 
     */
    public function toggleGoodsFavorite()
    {
        $goods_id = $this->request->post('goods_id', 0);

        if (empty($goods_id)) {
            return $this->error('参数错误');
        }

        // 验证商品是否存在
        $goods = GoodsModel::where(['id' => $goods_id, 'status' => 1])->find();
        if (empty($goods)) {
            return $this->error('商品不存在或已下架');
        }

        // 切换收藏状态
        $result = UserFavorite::toggleFavorite($this->user_id, $goods_id, 1);

        if ($result['code'] == 1) {
            return $this->success($result['msg'], ['is_favorited' => $result['is_favorited']]);
        } else {
            return $this->error($result['msg']);
        }
    }

}